package facade;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;

import Entidade.Home;
import Entidade.Material;
import VO.HomeVO;
import VO.MaterialVO;

public class FacadeHomeImpl implements facadeHome {

	public static String entidade ="sistemaDarlan";
	
	public HomeVO buscaHome(Integer id) throws TrataErroPersistecia {
		Home m = new Home();
		HomeVO vo = new HomeVO();
		
		 try{
			  EntityManager manager = Persistence.createEntityManagerFactory(entidade).createEntityManager();
			manager.getTransaction().begin();
		     m = (Home) manager.find(Home.class,id);
		     
		     vo.setId(m.getId());
		     vo.setTexto(m.getTexto());
		     vo.setTitulo(m.getTitulo());
		   
		    
		    manager.getTransaction().commit();
		    manager.close();
		    
		    return vo;
		  }catch  (Exception e){
			    e.getMessage();
			
		  }
		return null;
	}

	public List<HomeVO> buscaTodosHome() throws TrataErroPersistecia {
		try{
		    EntityManager manager = Persistence.createEntityManagerFactory(entidade).createEntityManager();
			Query q = manager.createQuery("from Home f");
		
			List<HomeVO>  ho= new ArrayList<HomeVO>();  
			
			List<Home> resultList =q.getResultList();
			
			for(Home m : resultList){
				
				HomeVO vo = new HomeVO();
				vo.setId(m.getId());
			    vo.setTexto(m.getTexto());
			    vo.setTitulo(m.getTitulo());
				
				ho.add(vo);
			}
				
			
			 
			return ho;
			
		}catch (Exception e){
			e.getMessage();
		}
		return null;
	}

	public void excluirHome(HomeVO vo) throws TrataErroPersistecia {
		Home m = new Home();
		 try{
			  EntityManager manager = Persistence.createEntityManagerFactory(entidade).createEntityManager();
		     manager.getTransaction().begin();
		     
		   
		    m = manager.find(Home.class,vo.getId());
		     
		     
		     manager.merge(m);
		     manager.remove(m);
		   
		    manager.getTransaction().commit();
		    manager.close();
		    
		  
		  }catch  (Exception e){
			    e.getMessage();
			
		  }
		
		
	}

	public void salvar(HomeVO vo)  {
		Home h = new Home();
		h.setId(vo.getId());
		h.setTexto(vo.getTexto());
		h.setTitulo(vo.getTitulo());
		
	  try{
		  EntityManager manager = Persistence.createEntityManagerFactory(entidade).createEntityManager();
		manager.getTransaction().begin();
	  
		if(h.getId()==null || h.getId().equals("0"))
	        manager.persist(h);
		else
			manager.merge(h);
	
	    manager.getTransaction().commit();
	    manager.close();
	    
	  }catch  (Exception e){
		    e.getMessage();
		
	  }
		
	}

}
